<template>
  <CustomerLayout>
    <div class="address-container">
      <!-- 页面标题 -->
      <div class="page-header">
        <div class="header-content">
          <h2>我的收货地址</h2>
          <el-button type="primary" size="default" @click="showAddDialog" class="add-btn">
            <el-icon><Plus /></el-icon>
            <span>添加地址</span>
          </el-button>
        </div>
      </div>
      
      <!-- 地址列表 -->
      <div v-if="addresses.length > 0" class="address-list">
        <div v-for="address in addresses" :key="address.id" class="address-item">
          <!-- 地址信息区域 -->
          <div class="address-info" @click="editAddress(address)">
            <div class="address-header">
              <span class="name">{{ address.name }}</span>
              <span class="phone">{{ address.phone }}</span>
              <el-tag v-if="address.isDefault" size="small" type="danger">默认</el-tag>
            </div>
            <div class="address-detail">
              {{ formatAddress(address) }}
            </div>
          </div>
          
          <!-- 操作区域 -->
          <div class="address-actions">
            <el-button link @click.stop="editAddress(address)">
              <el-icon><EditPen /></el-icon>
              <span>编辑</span>
            </el-button>
            <el-button link @click.stop="confirmDelete(address)">
              <el-icon><Delete /></el-icon>
              <span>删除</span>
            </el-button>
            <el-button 
              v-if="!address.isDefault" 
              link 
              @click.stop="setAsDefault(address.id)"
            >
              <el-icon><Star /></el-icon>
              <span>设为默认</span>
            </el-button>
          </div>
        </div>
      </div>
      
      <!-- 空状态 -->
      <el-empty 
        v-else-if="!loading"
        description="暂无收货地址" 
        :image-size="200"
      >
        <el-button type="primary" @click="showAddDialog">添加新地址</el-button>
      </el-empty>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="3" animated />
        <el-skeleton :rows="3" animated style="margin-top: 20px" />
      </div>
      
      <!-- 编辑/添加地址弹窗 -->
      <el-dialog
        v-model="dialogVisible"
        :title="isEditing ? '编辑地址' : '新增地址'"
        width="90%"
        max-width="500px"
      >
        <address-form 
          :address="currentAddress" 
          @submit="submitAddress" 
          @cancel="dialogVisible = false"
        />
      </el-dialog>
    </div>
  </CustomerLayout>
</template>

<script setup lang="ts">
import { ref, onMounted, onActivated } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus, EditPen, Delete, Star } from '@element-plus/icons-vue';
import CustomerLayout from '@/components/customer/CustomerLayout.vue';
import AddressForm from '@/components/customer/AddressForm.vue';
import { addressApi } from '@/api/customer';
import { Address } from '@/types/customer';

// 地址列表状态
const addresses = ref<Address[]>([]);
const loading = ref(false);

// 地址表单状态
const dialogVisible = ref(false);
const isEditing = ref(false);
const currentAddress = ref<Partial<Address>>({
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  detail: '',
  isDefault: false
});

// 获取地址列表 - 参照微信小程序的数据处理逻辑
const fetchAddresses = async () => {
  try {
    loading.value = true;
    console.log('开始加载地址列表');
    
    const response = await addressApi.getList();
    console.log('地址API返回数据:', response);
    
    // 处理API返回数据，支持多种数据结构
    const addressData = response.data?.data || response.data || [];
    
    if (!Array.isArray(addressData)) {
      console.warn('地址数据格式异常:', addressData);
      addresses.value = [];
      return;
    }
    
    // 处理地址数据，确保字段名称映射正确
    addresses.value = addressData.map(addr => ({
      id: addr.id,
      name: addr.receiver || addr.name, // 兼容不同字段名
      phone: addr.phone,
      province: addr.province,
      city: addr.city,
      district: addr.district,
      detail: addr.detailAddress || addr.detail, // 兼容不同字段名
      isDefault: addr.isDefault,
      // 保留原始字段，便于API调用时使用
      receiver: addr.receiver,
      detailAddress: addr.detailAddress
    }));
    
    console.log('处理后的地址数据:', addresses.value);
    
  } catch (error: any) {
    console.error('获取地址失败:', error);
    ElMessage.error(error.message || '获取地址列表失败');
    addresses.value = [];
  } finally {
    loading.value = false;
  }
};

// 格式化地址信息
const formatAddress = (address: Address): string => {
  return `${address.province} ${address.city} ${address.district} ${address.detail}`;
};

// 打开添加地址对话框
const showAddDialog = () => {
  isEditing.value = false;
  currentAddress.value = {
    name: '',
    phone: '',
    province: '',
    city: '',
    district: '',
    detail: '',
    isDefault: false
  };
  dialogVisible.value = true;
};

// 打开编辑地址对话框
const editAddress = (address: Address) => {
  isEditing.value = true;
  currentAddress.value = { ...address };
  dialogVisible.value = true;
};

// 设置默认地址 - 参照微信小程序的处理逻辑
const setAsDefault = async (addressId: number) => {
  try {
    loading.value = true;
    console.log('设置默认地址, ID:', addressId);
    
    // 参照微信小程序，先更新地址为默认，再调用设为默认接口
    await addressApi.setDefault(addressId);
    
    ElMessage.success('已设置为默认地址');
    
    // 更新本地地址列表 - 将所有地址的默认状态重置，然后设置当前地址为默认
    addresses.value = addresses.value.map(addr => ({
      ...addr,
      isDefault: addr.id === addressId
    }));
    
    console.log('默认地址设置成功');
    
  } catch (error: any) {
    console.error('设置默认地址失败:', error);
    ElMessage.error(error.message || '设置默认地址失败');
    
    // 失败时重新加载地址列表，确保数据一致性
    await fetchAddresses();
  } finally {
    loading.value = false;
  }
};

// 确认删除地址 - 增强错误处理和数据同步
const confirmDelete = (address: Address) => {
  ElMessageBox.confirm(
    `确定要删除地址"${formatAddress(address)}"吗?`,
    '删除地址',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      console.log('开始删除地址, ID:', address.id);
      
      await addressApi.delete(address.id);
      ElMessage.success('地址删除成功');
      
      // 从列表中移除被删除的地址
      addresses.value = addresses.value.filter(addr => addr.id !== address.id);
      
      console.log('地址删除成功，已从本地列表移除');
      
    } catch (error: any) {
      console.error('删除地址失败:', error);
      ElMessage.error(error.message || '删除地址失败');
      
      // 删除失败时重新加载地址列表，确保数据一致性
      await fetchAddresses();
    }
  }).catch(() => {
    console.log('用户取消删除操作');
  });
};

// 提交地址表单 - 完善数据处理和错误处理
const submitAddress = async (formData: Partial<Address>) => {
  try {
    loading.value = true;
    console.log('提交地址表单, 数据:', formData);
    
    // 数据校验 - 参照微信小程序的校验逻辑
    if (!formData.name) {
      ElMessage.error('请输入收货人姓名');
      return;
    }
    if (!formData.phone || !/^1\d{10}$/.test(formData.phone)) {
      ElMessage.error('请输入正确的手机号');
      return;
    }
    if (!formData.province || !formData.city || !formData.district) {
      ElMessage.error('请选择省市区');
      return;
    }
    if (!formData.detail) {
      ElMessage.error('请输入详细地址');
      return;
    }
    
    // 转换字段名以匹配API文档
    const apiData = {
      receiver: formData.name || '',
      phone: formData.phone || '',
      province: formData.province || '',
      city: formData.city || '',
      district: formData.district || '',
      detailAddress: formData.detail || '',
      isDefault: formData.isDefault || false
    };
    
    console.log('准备提交的API数据:', apiData);
    
    if (isEditing.value && currentAddress.value.id) {
      // 更新地址
      console.log('更新地址, ID:', currentAddress.value.id);
      const response = await addressApi.update(currentAddress.value.id, apiData);
      ElMessage.success('地址更新成功');
      
      // 处理返回数据并更新本地列表
      const updatedAddress = response.data?.data || response.data;
      
      if (formData.isDefault) {
        // 如果设为默认地址，需要更新其他地址的默认状态
        addresses.value = addresses.value.map(addr => ({
          ...addr,
          isDefault: addr.id === currentAddress.value.id,
          // 如果是当前更新的地址，更新所有字段
          ...(addr.id === currentAddress.value.id ? {
            name: formData.name,
            phone: formData.phone,
            province: formData.province,
            city: formData.city,
            district: formData.district,
            detail: formData.detail
          } : {})
        }));
      } else {
        // 只更新当前地址
        const index = addresses.value.findIndex(addr => addr.id === currentAddress.value.id);
        if (index !== -1) {
          addresses.value[index] = {
            ...addresses.value[index],
            name: formData.name || addresses.value[index].name,
            phone: formData.phone || addresses.value[index].phone,
            province: formData.province || addresses.value[index].province,
            city: formData.city || addresses.value[index].city,
            district: formData.district || addresses.value[index].district,
            detail: formData.detail || addresses.value[index].detail,
            isDefault: formData.isDefault || false
          };
        }
      }
      
    } else {
      // 添加新地址
      console.log('添加新地址');
      const response = await addressApi.add(apiData);
      ElMessage.success('地址添加成功');
      
      // 处理返回数据
      const newAddress = response.data?.data || response.data;
      
      if (formData.isDefault) {
        // 如果添加的是默认地址，需要更新其他地址的默认状态
        addresses.value = addresses.value.map(addr => ({
          ...addr,
          isDefault: false
        }));
      }
      
      // 将新地址添加到列表
      if (newAddress && newAddress.id) {
        addresses.value.push({
          id: newAddress.id,
          name: newAddress.receiver || formData.name || '',
          phone: newAddress.phone || formData.phone || '',
          province: newAddress.province || formData.province || '',
          city: newAddress.city || formData.city || '',
          district: newAddress.district || formData.district || '',
          detail: newAddress.detailAddress || formData.detail || '',
          isDefault: newAddress.isDefault || formData.isDefault || false
        });
      } else {
        // 如果没有返回完整数据，重新获取地址列表
        console.log('未获取到完整的新地址数据，重新加载地址列表');
        await fetchAddresses();
      }
    }
    
    dialogVisible.value = false;
    console.log('地址保存成功');
    
  } catch (error: any) {
    console.error('保存地址失败:', error);
    ElMessage.error(error.message || '保存地址失败');
  } finally {
    loading.value = false;
  }
};

// 组件挂载时获取地址列表 - 参照微信小程序的onLoad和onShow
onMounted(() => {
  console.log('AddressView组件已挂载，开始加载地址列表');
  fetchAddresses();
});

// 监听页面激活，实现类似微信小程序onShow的效果
onActivated(() => {
  console.log('AddressView页面激活，重新加载地址列表');
  fetchAddresses();
});
</script>

<style scoped>
.address-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 15px;
}

.header-content h2 {
  font-size: 20px;
  color: #333;
  margin: 0;
  flex: 1;
}

.add-btn {
  flex-shrink: 0;
  border-radius: 8px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.add-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.address-list {
  margin-bottom: 20px; /* 移除为底部按钮预留的空间 */
}

.address-item {
  background-color: #fff;
  border-radius: 8px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.address-info {
  cursor: pointer;
}

.address-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
}

.name {
  font-size: 16px;
  font-weight: bold;
  margin-right: 10px;
}

.phone {
  font-size: 14px;
  color: #666;
  margin-right: 10px;
}

.address-detail {
  font-size: 14px;
  color: #333;
  line-height: 1.5;
  margin-bottom: 10px;
}

.address-actions {
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #eee;
  padding-top: 10px;
  margin-top: 5px;
}

.address-actions .el-button {
  margin-left: 15px;
}

.loading-container {
  padding: 20px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .header-content {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }
  
  .header-content h2 {
    text-align: center;
  }
  
  .add-btn {
    width: 100%;
    justify-content: center;
  }
  
  .address-actions {
    flex-wrap: wrap;
  }
  
  .address-actions .el-button {
    margin-top: 5px;
  }
}
</style>
